package com.wangbo.springmvc002.daoimpl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.wangbo.springmvc002.dao.BaseDao;
@Repository
public class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK>{
	private Class<T> entityClass;
	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {
		this.entityClass = null;
        Class c = getClass();
        Type type = c.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
            this.entityClass = (Class<T>) parameterizedType[0];
        }
        System.out.println("-------------entityClass-----------"+entityClass);
	}
	@SuppressWarnings("unchecked")
	public T get(PK id) {
		Assert.notNull(id, "id is required");
		return (T) getSession().get(entityClass, id);
	}
	public List find(String hql,Object... values){
		
		return createQuery(hql, values).list();
		
	}
	public Query createQuery(String queryString,Object... values){
		Assert.hasText(queryString);
		Query queryObject = getSession().createQuery(queryString);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				queryObject.setParameter(i, values[i]);
			}
		}
		System.out.println(queryObject);
		return queryObject;
	}
	
	protected SessionFactory sessionFactory;
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	protected Session getSession() {
		System.out.println(sessionFactory);
		return sessionFactory.getCurrentSession();
	}

}
